import java.io.*;
import java.net.*;
import model.UserDAO;

import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;

import org.mybeans.dao.DAOException;
import org.mybeans.factory.BeanTable;

public class DroidChatServer{
	//private ArrayList<clientThread> pool = new ArrayList<clientThread>();
	
	public static void main(String args[]) {
		Socket clientSocket = null; // client socket
		SSLServerSocket sslserversocket = null; // server socket
		
		String jdbcDriver = "com.mysql.jdbc.Driver";
        String jdbcURL    = "jdbc:mysql:///DroidChat";
        String userName   = null;
        String password   = null;

        BeanTable.useJDBC(jdbcDriver,jdbcURL,userName,password);
		
		UserDAO userDAO = null;
		try {
			userDAO = new UserDAO();
		} catch (DAOException e2) { e2.printStackTrace(); }
		
		System.setProperty( "javax.net.ssl.keyStore", "DroidChatKeystore");
		System.setProperty( "javax.net.ssl.keyStorePassword", "123456"); 
    	System.setProperty( "java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
    	System.setProperty( "javax.net.debug", "ssl");
		
		// The default port
		int port_number=2222;
		
		if (args.length < 1)
		{
			System.out.println("Usage: java MultiThreadChatServer \n" + "Now using port number="+port_number);
		} else {
			port_number=Integer.valueOf(args[0]).intValue();
		}
		
		SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
		try {
			sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(port_number);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		// Create a socket object from the ServerSocket to listen and accept connections.
		// Open input and output streams for this socket will be created in client's thread
		// since every client is served by the server in an individual thread
		while(true){
			try {
				System.out.println("calling accept()");
				SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();
				System.out.println("accept() returns");
				clientThread client = new clientThread(sslsocket, userDAO);
				client.start();
			}catch (IOException e) {
				System.out.println(e);
			}
		}
	}
}
